import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from app.core.config import settings
from typing import Optional
from ..core.logger import get_logger

logger = get_logger('services.email_service')

class EmailService:
    @staticmethod
    def send_email(to_email: str, subject: str, body: str) -> bool:
        """
        发送邮件
        
        Args:
            to_email: 收件人邮箱
            subject: 邮件主题
            body: 邮件内容
            
        Returns:
            bool: 发送成功返回True，否则返回False
        """
        if not settings.EMAIL_ENABLED:
            logger.warning("Email service is disabled")
            return False
            
        try:
            # 创建邮件对象
            msg = MIMEMultipart()
            msg['From'] = f"{Header(settings.EMAIL_FROM_NAME, 'utf-8').encode()} <{settings.EMAIL_FROM_ADDRESS}>"
            msg['To'] = to_email
            msg['Subject'] = Header(subject, 'utf-8')
            
            # 添加邮件正文
            msg.attach(MIMEText(body, 'html', 'utf-8'))
            
            # 连接SMTP服务器并发送邮件
            server = smtplib.SMTP(settings.EMAIL_HOST, settings.EMAIL_PORT)
            if settings.EMAIL_USE_TLS:
                server.starttls()
            
            server.login(settings.EMAIL_USERNAME, settings.EMAIL_PASSWORD)
            server.send_message(msg)
            server.quit()
            
            logger.info(f"Email sent successfully to {to_email}")
            return True
            
        except Exception as e:
            logger.error(f"Failed to send email to {to_email}: {str(e)}")
            return False

    @staticmethod
    def send_password_reset_email(to_email: str, reset_token: str) -> bool:
        """
        发送密码重置邮件
        
        Args:
            to_email: 收件人邮箱
            reset_token: 重置令牌
            
        Returns:
            bool: 发送成功返回True，否则返回False
        """
        subject = "密码重置请求"
        
        # 生成重置链接（这里使用示例URL，实际应替换为您的前端URL）
        reset_link = f"http://localhost:5173/reset-password-confirm?token={reset_token}"
        
        body = f"""
        <html>
        <body>
            <h2>密码重置请求</h2>
            <p>您好，</p>
            <p>您收到此邮件是因为您请求重置您的账户密码。</p>
            <p>请点击以下链接重置您的密码：</p>
            <p><a href="{reset_link}" target="_blank">重置密码</a></p>
            <p>如果链接无法点击，请复制以下地址到浏览器中打开：</p>
            <p>{reset_link}</p>
            <p>如果您没有请求重置密码，请忽略此邮件。</p>
            <br>
            <p>此链接将在1小时内过期。</p>
            <br>
            <p>谢谢！</p>
            <p>RAGent Platform 团队</p>
        </body>
        </html>
        """
        
        return EmailService.send_email(to_email, subject, body)